﻿// <copyright file="MouseInputManager.Touch.cs" company="ThorIndustry">Copyright (c) ThorIndustry. All rights reserved.</copyright>

public partial class MouseInputManager
{
    private UnityEngine.Vector2 touchVector;
    private int firstFingerId = -1;
    private int secondFingerId = -1;

    private int lastTouchCount = 0;
    private float lastRotation = 0;

    private bool UpdateTouch()
    {
        bool hasRotate = false;

        // Rotation.
        int touchCount = UnityEngine.Input.touchCount;
        this.lastTouchCount = touchCount;
        if (touchCount >= 2 &&
            this.SelectedShape != null)
        {
            // We need only the first two... but... I cannot force the user to not touch the screen...
            UnityEngine.Vector2 currentVector = UnityEngine.Input.touches[0].position - UnityEngine.Input.touches[1].position;
            currentVector.Normalize();

            // We have to verify that previous and actual finger are the same.
            // Otherwise, just reset the whole stuff.
            if (this.firstFingerId == UnityEngine.Input.touches[0].fingerId &&
                this.secondFingerId == UnityEngine.Input.touches[1].fingerId)
            {
                // Compute the rotation.
                if (this.touchVector != currentVector)
                {
                    float rotation = UnityEngine.Vector2.Angle(this.touchVector, currentVector);

                    float det = this.touchVector.x * currentVector.y - this.touchVector.y * currentVector.x;
                    if (det > 0)
                    {
                        rotation = -rotation;
                    }
                    
                    if (rotation != this.lastRotation)
                    {
                        this.SelectedShape.transform.RotateAround(this.SelectedShape.GetCenter(), UnityEngine.Vector3.forward, this.lastRotation - rotation);
                        this.lastRotation = rotation;
                    }
                }
            }
            else
            {
                this.firstFingerId = UnityEngine.Input.touches[0].fingerId;
                this.secondFingerId = UnityEngine.Input.touches[1].fingerId;

                this.touchVector = currentVector;
                this.lastRotation = 0;
            }

            hasRotate = true;
        }
        else
        {
            if (this.firstFingerId != -1 &&
                this.SelectedShape != null)
            {
                this.SelectedShape.Snap(this.puzzleView.SolutionShape);
                hasRotate = true;
            }

            this.firstFingerId = -1;
            this.secondFingerId = -1;
            this.lastRotation = 0;
        }

        return hasRotate;
    }
}
